/**
 * Created by Mark on 2018/4/17.
 * 收货地址业务逻辑处理
 */

var _mm = require("util/mm.js");
var _cities = require("util/cities/cities.js");
var _address = require("service/address-service.js");
var addressModelTemplateHtml = require("./address-model.string");

var _addressModel = {
    show : function(option){
        this.option = option;//option对象有三个参数（isUpdate,data,onSuccess）(是否更新，服务器response的数据,回调函数)
        this.option.data  = option.data || {};//缓存从服务器response数据
        this.$modelWrap = $(".model-wrap");//缓存弹出框
        this.loadModel();//渲染页面
        this.bindEvent();//事件绑定
    },
    bindEvent : function () {
        this.hideAddressModel();//退出弹框事件(点击X，蒙板时触发)
        this.selectProvinces();//选择省份后和 该省份的城市二级联动
        this.clickAddressBtn();//点击保存收货地址按钮事件（新增、修改地时触发）
        this.clickResetAddressBtn();
    },

    //1.数据渲染
    loadModel : function(){//1.1渲染省份的数据
        var addressModelHtml = _mm.renderHtml(addressModelTemplateHtml,{
            isUpdate : this.option.isUpdate,
            data : this.option.data
        });
        this.$modelWrap.html(addressModelHtml);//渲染HTML
        this.loadProvince();//加载省份
    },
    loadProvince : function(){//1.1加载省份
        var provinces = _cities.getProvinces(),
            $provincesSelect = this.$modelWrap.find("#receiver-province");
        var  provincesHtml = this.getSelectionOption(provinces);
        $provincesSelect.html(provincesHtml);

        if(this.option.isUpdate && this.option.data.receiverProvince){//如果是更新操作需要回填省份信息
            var provinceName = this.option.data.receiverProvince;
            $provincesSelect.val(provinceName);//省份回填
            this.loadCities(provinceName);//根据省份信息将城市回填
        }
    },
    loadCities : function (provinceName) {//1.2加载省份下的城市
        var cities = _cities.getCities(provinceName),
            $citiesSelect = this.$modelWrap.find("#receiver-city"),
            citiesHtml = this.getSelectionOption(cities);
        $citiesSelect.html(citiesHtml);

        if(this.option.isUpdate && this.option.data.receiverCity){//如果是更新操作需要回填城市信息
            $citiesSelect.val(this.option.data.receiverCity);//城市回填
        }
    },

    //2.事件绑定
    hideAddressModel: function () {//2.1退出弹框事件
        var _this = this;
        this.$modelWrap.find(".model-container").click(function (e) {//防止点击内容区的时候也关闭弹窗
            e.stopPropagation();//停止事件冒泡
        });
        this.$modelWrap.find(".close").click(function () {//点击X号或者蒙板关闭弹窗
            _this.hideModel();
        });
    },
    selectProvinces : function () {//2.2选择省份后和 该省份的城市二级联动
        var _this = this;
        this.$modelWrap.find("#receiver-province").change(function () {
            var selectProvince = $(this).val();
            _this.loadCities(selectProvince);
        });
    },
    clickAddressBtn : function () {//2.3点击保存收货地址按钮事件
        var _this = this;
        this.$modelWrap.find(".address-btn").click(function () {
            var receiverResult = _this.getReceiverInfo(),
                isUpdate = _this.option.isUpdate;

            //新增地址操作
            if(!isUpdate && receiverResult.status){
                _address.save(receiverResult.data,
                    function (res) {
                        _mm.successTips("已经成功添加收货地址");
                        _this.hideModel();//隐藏弹框
                        typeof  _this.option.onSuccess() === "function"
                            && _this.option.onSuccess(res.data);//回调函数
                }, function (err) {
                    _mm.errorTips(err.msg);
                });
            }

            //编辑地址操作
            else if(isUpdate && receiverResult.status){
                _address.updateAddress(receiverResult.data, function (res) {
                    _mm.successTips("修改收货地址成功");
                    _this.hideModel();//隐藏弹框
                    typeof  _this.option.onSuccess() === "function"
                    && _this.option.onSuccess(res.data);//回调函数
                }, function (err) {
                    _mm.errorTips(err.msg);
                });
            }else{
                _mm.errorTips(receiverResult.errMsg)
            }
        });
    },
    clickResetAddressBtn : function () {
        var _this = this;
        this.$modelWrap.find(".reset-btn").click(function (){
            _this.$modelWrap.find("#receiver-name").val("");
            _this.$modelWrap.find("#receiver-province").val("");
            _this.$modelWrap.find("#receiver-city").val("");
            _this.$modelWrap.find("#receiver-city").val("");
            _this.$modelWrap.find("#receiver-phone").val("");
            _this.$modelWrap.find("#receiver-zip").val("");
        });
    },

    //3.辅助函数
    getSelectionOption : function(optionArray){//3.1将数组数据封装成HTMl
        var html = '<option value="">请选择</option>';
        var i;
        for(i = 0 ,iLength = optionArray.length; i < iLength ;i++){
            html += '<option value="'+optionArray[i]+'">'+optionArray[i]+'</option>'
        }
        return html;
    },

    hideModel : function () {//3.2关闭弹窗
        this.$modelWrap.empty();
    },

    getReceiverInfo : function () {//3.3获取表单里信息
        var receiverInfo = {},
            result = {
                status : false,
                errMsg : "",
                data : null
            };
        receiverInfo.receiverName = $.trim(this.$modelWrap.find("#receiver-name").val());
        receiverInfo.receiverProvince = $.trim(this.$modelWrap.find("#receiver-province").val());
        receiverInfo.receiverCity = $.trim(this.$modelWrap.find("#receiver-city").val());
        receiverInfo.receiverAddress = $.trim(this.$modelWrap.find("#receiver-address").val());
        receiverInfo.receiverPhone = $.trim(this.$modelWrap.find("#receiver-phone").val());
        receiverInfo.receiverZip = $.trim(this.$modelWrap.find("#receiver-zip").val());
        if(this.option.isUpdate){//如果是更新操请求数据需要加入id
            receiverInfo.id = $.trim(this.$modelWrap.find("#receiver-id").val());
        }
        if(!receiverInfo.receiverName){
            result.errMsg = "请输入收件人姓名";
            return result;
        }else if(!receiverInfo.receiverProvince){
            result.errMsg = "请选择省份";
            return result;
        }else if(!receiverInfo.receiverCity){
            result.errMsg = "请选择城市";
            return result;
        }else if(!receiverInfo.receiverAddress){
            result.errMsg = "请输入详细地址";
            return result;
        }else if(!receiverInfo.receiverPhone){
            result.errMsg = "请输入收件人的联系电话";
            return result;
        }else if(!_mm.validate (receiverInfo.receiverPhone,"phone")){
            result.errMsg = "联系电话格式不正确";
            return result;
        }
        else{//验证通过
            result.status = true;
            result.data = receiverInfo;
        }
        return result;
    }
};
module.exports = _addressModel;